const { DataTypes, Op } = require('sequelize');
const config = require('../config/config');

module.exports = (sequelize) => {
  // 定义验证码模型
  const VerificationCode = sequelize.define('VerificationCode', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: '验证码ID'
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '邮箱地址'
    },
    code: {
      type: DataTypes.STRING(10),
      allowNull: false,
      comment: '验证码'
    },
    type: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: '验证码类型：login-登录，register-注册，bind-绑定账号'
    },
    expires_at: {
      type: DataTypes.DATE,
      allowNull: false,
      comment: '过期时间'
    },
    is_used: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: '是否已使用'
    }
  }, {
    tableName: 'verification_codes',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: false
  });

  // 生成随机验证码
  VerificationCode.generateCode = () => {
    return Math.floor(100000 + Math.random() * 900000).toString();
  };

  // 创建验证码
  VerificationCode.createCode = async (email, type) => {
    try {
      // 生成6位随机验证码
      const code = Math.floor(100000 + Math.random() * 900000).toString();
      
      // 设置过期时间
      const expiresAt = new Date();
      expiresAt.setMinutes(expiresAt.getMinutes() + config.verification.expireMinutes);
      
      // 先检查是否已存在该邮箱的验证码
      const existingCode = await VerificationCode.findOne({
        where: {
          email,
          type
        }
      });
      
      if (existingCode) {
        // 如果存在，更新验证码和过期时间
        await existingCode.update({
          code,
          expires_at: expiresAt,
          is_used: false
        });
        return existingCode;
      } else {
        // 如果不存在，创建新记录
        const newCode = await VerificationCode.create({
          email,
          code,
          type,
          expires_at: expiresAt,
          is_used: false
        });
        return newCode;
      }
    } catch (error) {
      console.error(`创建验证码过程发生错误:`, error);
      throw error;
    }
  };

  // 验证验证码
  VerificationCode.verifyCode = async (email, code, type) => {
    try {
      // 查找验证码记录
      const verificationCode = await VerificationCode.findOne({
        where: {
          email,
          code,
          type,
          is_used: false
        }
      });
      
      // 如果验证码不存在
      if (!verificationCode) {
        return {
          valid: false,
          message: '验证码无效'
        };
      }
      // 检查验证码是否过期
      const now = new Date();
      const expiresAt = new Date(verificationCode.expires_at);
      
      if (now > expiresAt) {
        return {
          valid: false,
          message: '验证码已过期'
        };
      }
      
      // 标记验证码为已使用
      await verificationCode.update({ is_used: true });
      return {
        valid: true,
        message: '验证成功'
      };
    } catch (error) {
      console.error(`验证验证码过程发生错误:`, error);
      return {
        valid: false,
        message: '验证失败，系统错误'
      };
    }
  };

  return VerificationCode;
}; 